﻿using System;
using System.Collections.Generic;
using System.Linq;
using TuxedoLib;

namespace SpaceSquirrel.Automation
{
	public class AcornAutomation : SpriteAutomation
	{
		private const double ACORN_SPEED = 1.5;
		private const int ACORN_DELAY_FOR_TOP_THROWING = 5 * 30;

		private int countdown;
		public string mode;
		private Sprite top;
		private bool walkingLeft;

		public AcornAutomation(Sprite sprite)
			: base(sprite)
		{
			this.sprite = sprite;
			this.countdown = Util.RandomInt(0, ACORN_DELAY_FOR_TOP_THROWING);
			this.mode = "patrolling"; // patrolling | throwing | baldpatrolling
			this.top = null;
			this.walkingLeft = true;
		}

		public override void DoStuff(PlayScene scene)
		{
			--this.countdown;
			bool walk = false;
			if (this.mode == "patrolling")
			{
				if (this.countdown <= 0)
				{
					this.mode = "throwing";
					this.top = new Sprite("acorntop", this.sprite.x, this.sprite.y);
					this.top.acornTopDir = this.sprite.lastDirection;
					this.top.goLeft = this.top.acornTopDir == "left";
					AcornTopAutomation automation = this.top.automation as AcornTopAutomation;
					automation.setGoLeft(this.sprite.lastDirection == "left");
					automation.setGoUp(this.sprite.y > scene.Player.y);
					automation.body = this.sprite;
					this.top.deleteWhenOffScreen = true; // wait, really? TODO: reassess this.
					this.top.ghost = true;
					this.top.floats = true;
					this.sprite.spawns = new List<Sprite>() { this.top };
				}
				else
				{
					walk = true;
				}
			}
			else if (this.mode == "throwing")
			{
				if (this.top.dead)
				{
					this.mode = "baldpatrolling";
				}
				else if (((AcornTopAutomation)this.top.automation).completed)
				{
					this.mode = "patrolling";
					this.top.dead = true;
					this.countdown = ACORN_DELAY_FOR_TOP_THROWING;
				}
			}
			else if (this.mode == "baldpatrolling")
			{
				walk = true;
			}

			if (walk)
			{
				if (this.sprite.collideWall)
				{
					this.walkingLeft = !this.walkingLeft;
				}

				Tile[][] tiles = scene.Tiles;
				int cols = scene.cols;
				int rows = scene.rows;
				double dx = this.walkingLeft ? ACORN_SPEED : -ACORN_SPEED;
				int oldTileX = (int)(this.sprite.modelX / 16);
				double newX = this.sprite.modelX + dx;
				int oldTileY = (int)(this.sprite.modelY / 16);
				int newTileX = (int)(newX / 16);
				if (newTileX < 0 || newTileX >= cols)
				{
					this.walkingLeft = !this.walkingLeft;
					return;
				}

				int belowTileY = oldTileY + 1;

				if (newTileX == oldTileX)
				{
					this.sprite.dx = dx;
				}
				else
				{
					if (belowTileY < 0 || belowTileY >= rows)
					{
						// uhhh....delete this if statement?
					}

					Tile t = tiles[newTileX][belowTileY];
					if (!t.solid && !t.isTop)
					{
						this.walkingLeft = !this.walkingLeft;
					}
					else
					{
						this.sprite.dx = dx;
					}
				}
			}
		}
	}
}
